package com.gxc.browser.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxc.core.config.SecurityProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证授权成功 Handler.
 * 需要加配置.
 *
 * @author GongXincheng
 * @since 2019-10-15 16:38
 */
@Slf4j
@Component
//public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private SecurityProperties securityProperties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        log.info("登录成功");

        // 如果配置的登录方式为JSON
        String loginType = securityProperties.getBrowser().getLoginType();
        if ("json".equalsIgnoreCase(loginType)) {
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.getWriter().write(objectMapper.writeValueAsString(authentication));
            response.getWriter().flush();
        } else {
            // SpringSecurity 默认实现跳转
            super.onAuthenticationSuccess(request, response, authentication);
        }
    }
}


/**
 * html-结果：
 * <p>
 * {
 * "authorities":[
 * {
 * "authority":"admin"
 * },
 * {
 * "authority":"gxc"
 * }
 * ],
 * "details":{
 * "remoteAddress":"127.0.0.1",
 * "sessionId":"ECF3DB92315E62EFB886D9AAE8C69A06"
 * },
 * "authenticated":true,
 * "principal":{
 * "password":null,
 * "username":"admin",
 * "authorities":[
 * {
 * "authority":"admin"
 * },
 * {
 * "authority":"gxc"
 * }
 * ],
 * "accountNonExpired":true,
 * "accountNonLocked":true,
 * "credentialsNonExpired":true,
 * "enabled":true
 * },
 * "credentials":null,
 * "name":"admin"
 * }
 */